怎么使用mongoose的geoNear - 莫纪祥的日志 - 网易博客

创建时间:2016/7/13 18:33
来源:http://blog.163.com/moji_xiang/blog/static/223422103201410263520531/


起因

在开发的时候碰到一个情况,数据源有100个景点,需要对给出的一个点,求距离它最近的景点,并且在前端下拉翻页的过程中,依距离顺序依次显示出来。大众点评做出了这个效果,但是以我现阶段的经验,想不出比较完美的解决方案。尤其是处理下拉翻页还能保证排序的效果,这一点是需要先对所有的点求距离,然后将所有点进行排序然后输出吗?这样效率不低吗?后来想到,mongodb有一个查询操作是geoNear,于是思考通过这种方案来解决排序效率的问题。

过程

在网上查了一下,大概需要三步:

  1. 确保有loc:[longitude, latitude]属性
  2. loc增加索引AttractionSchema.index({loc: '2d'});
  3. 使用geoNear

    Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err,results, stats) {
         console.log(results);
    });
    

或者确保有

  1. 确保有GeoJSON数据结构

    { <location field>: { type: "<GeoJSON type>" , coordinates: <coordinates> } }
    
  2. 增加索引AttractionSchema.index({location: '2dsphere'});
  3. 查找

     // geoJson
     var point = { type : "Point", coordinates : [9,9] };
     Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err,     results, stats) {
        console.log(results);
     });
    

扩展

利用aggregate

models.Attraction.aggregate(
    [{
        "$geoNear": {
            // "near": {
            //         "type": "Point",
            //         "coordinates": [-74.00824900000001, 40.708635]
            //     },
            "near": [-74.00824900000001, 40.708635],
            "maxDistance": 10000,
            "distanceMultiplier": 6371,
            "spherical": true,
            "query":{cityid: '516cc44ce3c6a60f69000011'},
            "distanceField": "dist.calculated",
            "includelocs":"dist.location"
        }
    },{

        "$skip": 10
    },{
        "$limit": 10
    }],
    function(err, docs) {
        if (err) {
            console.log(err);
        } else {
            docs.forEach(function(element, index){
                console.log(element.cityname + ' '+element.attractions + ' '+ element.dist.calculated);
            });
        }
        // These are not mongoose documents, but you can always cast them
    }
);
?
阅读(300)| 评论(0)
       

用微信  “扫一扫”

将文章分享到朋友圈。

 

用易信  “扫一扫”

将文章分享到朋友圈。

 
喜欢 推荐 转载
.